<?php

namespace app\user\controller;
use org\Tree;

class Supply extends base
{
//前置方法
    protected $beforeActionList = [
        'chackUser' => ['only' => 'index,edit'],
        'addclass' => ['only' => 'edit'],
        'map' => ['only' => 'index'],
    ];

    protected function chackUser()
    {
        if (empty($this->getLoginUser()->status)) {
            $this->error(lang('Not open this feature'));
        }
    }

    /**
     * 搜索
     */
    protected function map()
    {
        if ($this->request->isGet()) {
            $data = $this->request->param();
            $this->datas = array();

            if (isset($data['status']) || !empty($data['status'])) {
                $this->datas ['status'] = $data['status'];
            }

            if (!empty($data['title'])) {
                $this->datas ['title'] = ['like', '%' . $data['title'] . '%'];
            }
        }
        $this->datas ['uid'] = $this->getLoginUser()->id;
    }



    /**
     * 栏目
     */
    protected function addclass()
    {
        $this->datas['lang'] = cookie('think_var');
        $this->datas['model']='Supply';
        $this->datas['status']='1';
        $nav = model('nav')->where($this->datas)->select();
        $auth_rule = Tree::Forlevel($nav,'|----','id','pid');
        $this->assign('Supplynav', $auth_rule);
    }


    public function edit()
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['status'] = 0;
            $data['uid'] = $this->getLoginUser()->id;
            $data['uname'] = $this->getLoginUser()->name;
            $validate = $data['id'] ? 'Supply.edit' : 'Supply.add';
            $result = $this->validate($data, $validate);
            if (true !== $result) {
                return ajax_info($result);
            }

            if (!empty($data['id'])) {
                return $this->update($data);
            }
            $data['lang']=cookie('think_var');

            $result = $this->model->allowField(true)->save($data);
            if ($result) {
                return ajax_info(lang('Submit successfully awaiting review'), 'y');

            }
            return ajax_info(lang('Submission Failed'));

        }
        $data = $this->model->where('id', $this->request->param('id'))->where('uid', $this->getLoginUser()->id)->find();
        $this->assign(['data' => $data]);
        return $this->fetch();
    }
}
